﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.EntityClient;
using System.Data.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using QMSDAL;

namespace QuaManSys.InnerInfo
{
    public partial class InnerInfoProcessing : System.Web.UI.Page
    {
        /// <summary>
        /// 根据入口加载相应页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];

            //判断用户是否是非法访问
            if (user.employeeId != "")
            {
                string dept = user.department;
                string state = Request.QueryString["state"];
                string quaId = Request.QueryString["id"];
                //根据状态、当前角色加载页面
                if (!IsPostBack)
                {
                    LoadDiffPage(state, quaId, user);

                }
            }
            else
            {
                //跳转到登录页面
                Response.Redirect("~/Login.aspx");
            }
        }
        #region 根据权限和信息表状态加载不同页面

        private void LoadDiffPage(string state, string id, CurUser user)
        {
            //读取当前用户权限
            string empId = user.employeeId;
            string roleAccess = "A";

            switch (state)
            {
                case "newId":
                    //判断是否具有登记权限
                    if (roleAccess == "C")
                    {
                        initPageRegist(user);

                        //停用用不上的按钮
                        pnlAddtion.Visible = false;
                        btnRollback.Visible = false;
                        btnInsertProinfo.Visible = false;
                        btnDistribute.Visible = false;
                        btnEvaluate.Visible = false;
                        btnInfoSub.Visible = false;

                    }
                    else
                    {
                        Response.Write("<script>alert('您不具有当前访问权限！')</script>");
                        Response.Redirect("InnerMainPage.aspx");
                    }
                    break;
                case "分发":
                    //判断是否具有分发权限
                    if (Permission.JudgePermission(user, "1B", "B0"))
                    {
                        if (!IsPostBack)
                        {
                            //GetProjectNumbers();
                            lblInfoNo.Text = Request.QueryString["id"];
                            initResponDept();
                            initddlProNo();

                            initRelatedDept();//初始化checkbox
                            //根据qualityInfoId显示信息
                            ShowInfo(lblInfoNo.Text);
                            
                            //停用用不上的按钮
                            btnRegist.Visible = false;
                            btnInsertProinfo.Visible = false;
                            btnEvaluate.Visible = false;
                            btnInfoSub.Visible = false;
                        }
                    }
                    else
                    {
                        Response.Write("<script>alert('您不具有当前访问权限！')</script>");
                        Response.Redirect("InnerMainPage.aspx");
                    }
                    break;
                case "处理":
                    //判断是否具有处理质量问题权限
                    if (Permission.JudgePermission(user, "1B", "B1"))
                    {
                        if (!IsPostBack)
                        {
                            lblInfoNo.Text = Request.QueryString["id"];
                            initResponDept();
                            initddlProNo();
                            ShowInfo(lblInfoNo.Text);
                            //CheckBox1.Enabled = false;
                            //CheckBox2.Enabled = false;

                            txtProDept.Text = user.department;
                            txtProName.Text = user.name;

                            PnlMainInfo.Enabled = false;
                            pnlProInfo.Visible = true;
                            btnRegist.Visible = false;
                            btnEvaluate.Visible = false;
                            btnInfoSub.Visible = false;
                            btnDistribute.Visible = false;
                        }
                    }

                    else
                    {
                        Response.Write("<script>alert('您不具有当前访问权限！')</script>");
                        Response.Redirect("InnerMainPage.aspx");
                    }
                    break;
                case "登记":
                    if (!IsPostBack)
                    {
                        //GetProjectNumbers();
                        lblInfoNo.Text = Request.QueryString["id"];
                        GetProjectNumbers();
                        initResponDept();
                        initRelatedDept();//初始化checkbox
                        //根据qualityInfoId显示信息
                        ShowInfo(lblInfoNo.Text);
                        

                        pnlAddtion.Visible = false;
                        //停用用不上的按钮
                        btnRollback.Visible = false;
                        btnInsertProinfo.Visible = false;
                        btnDistribute.Visible = false;
                        btnEvaluate.Visible = false;
                        btnInfoSub.Visible = false;
                    }
                    txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
                    txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
                    //txtDeptFoc.Attributes.Add("ReadOnly", "True");
                    break;
                case "归档":
                    if (!IsPostBack)
                    {
                        //GetProjectNumbers();
                        lblInfoNo.Text = Request.QueryString["id"];
                        initResponDept();
                        initddlProNo();
                        initRelatedDept();//初始化checkbox
                        //根据qualityInfoId显示信息
                        ShowInfo(lblInfoNo.Text);
                        
                        PnlMainInfo.Enabled = false;
                        pnlRslEva.Visible = true;
                        //pnlProInfo.Visible = true;

                        //停用用不上的按钮
                        btnRegist.Visible = false;
                        btnRollback.Visible = false;
                        btnInsertProinfo.Visible = false;
                        btnDistribute.Visible = false;
                        //btnEvaluate.Visible = false;
                        if (roleAccess != "A")
                        {
                            btnInfoSub.Visible = false;
                        }

                    }
                    break;
                default:
                    if (!IsPostBack)
                    {
                        //GetProjectNumbers();
                        lblInfoNo.Text = Request.QueryString["id"];
                        initResponDept();
                        initddlProNo();
                        initRelatedDept();//初始化checkbox
                        //根据qualityInfoId显示信息
                        ShowInfo(lblInfoNo.Text);
                        
                    }
                    break;
            }
            initAttatchment();
        }

        #endregion

        #region 初始化新增页面

        /// <summary>
        /// 初始化新增页面
        /// </summary>
        private void initPageRegist(CurUser user)
        {
            if (!IsPostBack)
            {
                //CurUser user = (CurUser)Session["CurUser"];
                txtInfoWrt.Text = user.employeeId;
                txtInfoDep.Text = user.department;
                txtWrtDat.Text = DateTime.Now.ToString("yyyy/MM/dd");
                GetProjectNumbers();
                initResponDept();//初始化责任部门
                initRelatedDept();//初始化checkbox
                txtProDL.Text = DateTime.Now.ToString("yyyy/MM/dd");
            }
            txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
            txtDeptFoc.Attributes.Add("ReadOnly", "True");
            string s = maxID();
            lblInfoNo.Text = AutoCreatID("HHM", s);
        }
        #endregion

        #region 生成自动编号

        /// <summary>
        /// 生成自动编号
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="TableName"></param>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public static string AutoCreatID(string flag, string maxID)
        {
            string dbDateTime = DateTime.Now.Year.ToString();
            //string Str = "select max(" + FieldName + ") id from " + TableName;//查询表中的字段
            //object obj = Datasource.DbHelperSQL.GetSingle(Str);//把查询字符串Str放到GetSingle()中执行查询(Command)并返回查询结果（对象）
            //string maxID = "";
            //if (obj != null)//返回（查询字符串）对象
            //    maxID = Datasource.DbHelperSQL.GetSingle(Str).ToString();
            string Result = "";
            if (maxID == "")//没有最大编号
            {
                Result = flag + DateTime.Now.Year + "001";//HHM2012001
            }
            else
            {
                //截取字符
                string strFirstFour = maxID.Substring(3, 4);
                string strLastThree = maxID.Substring(7, 3);
                if (dbDateTime == strFirstFour)//截取的最大编号（20090225）是否和数据库服务器系统时间相等
                {
                    string strNewThree = (Convert.ToInt32(strLastThree) + 1).ToString("000");//0000+1
                    Result = flag + DateTime.Now.Year + strNewThree;//HHM2012001
                }
                else
                {
                    Result = flag + DateTime.Now.Year + "001";
                }
            }
            return Result;
        }

        #endregion

        #region 找最大的自动生成单号

        /// <summary>
        /// 找最大的自动生成单号
        /// </summary>
        public static string maxID()
        {
            var context = new QuaManSysEntities();

            if (context.InnerQualityInfo.Count() == 0)
            {
                return "";

            }
            else
            {
                var query = from b in context.InnerQualityInfo
                            orderby b.qualityInfoId
                            select b.qualityInfoId;
                return query.Max();

            }
        }
        #endregion

        #region 获取后台所有工程编号

        /// <summary>
        /// 将工程编号和后台数据库绑定
        /// </summary>
        private void GetProjectNumbers()
        {
            DataSet myDs = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in myDs.Tables)
            {
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Columns.Count; curRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
            }
        }
        #endregion

        #region 初始化责任部门

        private void initResponDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                DDLDepRes.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        DDLDepRes.Items.Insert(count++, li);
                    }
                }
            }
        }
        #endregion

        #region 初始化相关部门

        /// <summary>
        /// 初始化checkbox
        /// </summary>
        private void initRelatedDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                txtDeptFoc.Text = "";
                cblKeyWords.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == DDLDepRes.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        cblKeyWords.Items.Insert(count++, li);
                    }
                }
            }
            
        }
        #endregion

        #region 初始化工程编号下拉框

        /// <summary>
        /// 初始化工程编号下拉框
        /// </summary>

        private void initddlProNo()
        {
            DataSet ds = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in ds.Tables)
            {
                ddlProNo.Items.Clear();
                int count = 0;
                for (int culCol = 0; culCol < dt.Columns.Count; culCol++)
                {
                    for (int culRow = 0; culRow < dt.Rows.Count; culRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[culRow][culCol].ToString());
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
            }

        }
        #endregion

        #region 通过qualityInfoId初始化显示信息

        /// <summary>
        ///通过qualityInfoId显示信息
        /// </summary>
        /// <param name="qualityInfoId"></param>
        protected void ShowInfo(string qualityInfoId)
        {
            using (var db = new QuaManSysEntities())
            {
                var query = db.InnerQualityInfo.Find(qualityInfoId);

                ddlProNo.Text = query.projectNo;    //加载工程编号

                txtComponent.Text = query.components;
                txtManufac.Text = query.producer;
                txtFaiTyp.Text = query.faultType;
                if (query.projectCategory == "已处理")
                    CheckBox1.Checked = true;
                else CheckBox2.Checked = true;
                txtPjNam.Text = query.name;
                string ss = Convert.ToString(query.deadline);
                txtProDL.Text = ss.Split(' ')[0];
                txtCustomer.Text = query.customerLinker;
                txtCusTel.Text = query.telephone;
                txtSpeReq.Text = query.specialDemands;
                DDLInfoCla.Text = query.informationSource;
                DDLImpLev.Text = query.levelOfImportance;
                txtInfoDsc.Text = query.description;
                txtInfoWrt.Text = query.registrantName; //显示名字
                txtInfoDep.Text = query.registrantDepart;
                //registDate = Convert.ToDateTime(txtWrtDat.Text),
                string ww = Convert.ToString(query.registDate);
                txtWrtDat.Text = ww.Split(' ')[0];
                txtReqAdv.Text = query.recommendedTreatPlan;

                lblState.Text = query.processingStatus;
                //if (query.processingStatus == "闭环")
                //    lblState.Text = "处理";
                txtReqRsl.Text = query.processingResults;
                txtProCmm.Text = query.processingAssess;
                txtPjCls.Text = query.informationCategory;
                foreach (var p in query.InnerResponsibleDepart)
                {
                    if (p.isResponDepart == 1)
                    {
                        //DDLDepRes.SelectedItem.Text=p.department;
                        DDLDepRes.Items[0].Text = p.department;

                        //DDLDepRes.SelectedValue = p.department;

                    }
                }
                string s = "";
                foreach (var p in query.InnerResponsibleDepart)
                {
                    if (p.qualityInfoId == qualityInfoId && p.isResponDepart == 0)
                    {
                        if (s == "") s += p.department;
                        else s += '|' + p.department;

                    }

                }

                txtDeptFoc.Text = s;
            }
            txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
        }
        #endregion

        #region 禁止修改信息项
        /// <summary>
        /// 禁止修改
        /// </summary>
        //   protected void Unenable()
        //{
        //    ddlProNo.Enabled = false;
        //    txtComponent.Enabled = false;
        //    txtManufac.Enabled =false;
        //    txtFaiTyp.Enabled = false;
        //    CheckBox1.Enabled = false;
        //    CheckBox2.Enabled = false;
        //    txtPjNam.Enabled = false;
        //    txtProDL.Enabled = false;
        //    txtCustomer.Enabled = false;
        //    txtCusTel.Enabled = false;
        //    txtSpeReq.Enabled = false;
        //    DDLInfoCla.Enabled = false;
        //    DDLImpLev.Enabled = false;
        //    txtInfoDsc.Enabled = false;
        //    txtInfoWrt.Enabled = false;
        //    txtInfoDep.Enabled = false;
        //    //registDate = Convert.ToDateTime(txtWrtDat.Text),
        //    txtWrtDat.Enabled = false;
        //    txtReqAdv.Enabled = false;
        //    lblState.Enabled = false;
        //    txtReqRsl.Enabled = true;
        //    txtProCmm.Enabled = true;
        //    txtPjCls.Enabled = false;
        //    DDLDepRes.Enabled = false;
        //    txtDeptFoc.Enabled = false;


        //}
        #endregion

        #region 责任（关注）部门处理信息事件

        /// <summary>
        /// 处理信息
        /// </summary>
        public void btnInsertProinfo_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有分发权限
            bool roleAccess = Permission.JudgePermission(user, "1B", "B1");
            string infoId = lblInfoNo.Text;
            string strDept = user.department;
            if (roleAccess)
            {
                fileUpload();
                ConcreteInsertProInfo(strDept, infoId);
                Common.InnerRelatedDeptOperation.AddInnerRelatedDept(lblInfoNo.Text, user.department);
                Response.Redirect("SubmitSuccess.aspx");
            }
            else
            {
                Response.Write("<script>alert('您不具有当前访问权限！')</script>");
            }
        }
        private void ConcreteInsertProInfo(string strDept, string infoId)
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    InnerQualityInfoPro Insertinfo = new InnerQualityInfoPro
                    {
                        processerDepart = txtProDept.Text,
                        processerName = txtProName.Text,
                        processingDate = Convert.ToDateTime(txtProDate.Text),
                        opinion = txtProOpn.Text,
                        qualityInfoId = lblInfoNo.Text
                    };

                    context.InnerQualityInfoPro.Add(Insertinfo);
                    context.SaveChanges();

                    //将当前处理部门的processed字段改为已处理（1）
                    var query =
                        (from d in context.InnerResponsibleDepart.
                        Where(no => no.qualityInfoId.Equals(lblInfoNo.Text)).
                        Where(ps => ps.department.Equals(strDept))
                         select d).Single();
                    query.processed = 1;
                    context.SaveChanges();

                    //若都处理过了，修改status字段
                    var queryProed =
                        from q in context.InnerResponsibleDepart
                        where q.qualityInfoId == lblInfoNo.Text && q.processed == 0
                        select q;
                    int relRecord = queryProed.Count();
                    if (relRecord == 0)
                    {
                        context.InnerQualityInfo.Find(lblInfoNo.Text).processingStatus = "处理";
                        context.SaveChanges();
                    }
                }
                catch
                {
                    Response.Write("<script>alert('处理更新失败')</script>");
                    //Response.Redirect("~/InnerInfo/InnerInfoReminderBox.aspx");
                }
            }

            Repeater1.DataSourceID = "EntityDataSource1";
            Repeater1.DataBind();
            //Repeater1.Controls[Repeater1.Items.Count + 1].Visible = false;

            
        }
        #endregion

        #region 回退事件的处理
        //回退事件处理
        protected void btnRollback_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有分发权限
            bool roleAccess = Permission.JudgePermission(user, "1B", "B2");
            if (roleAccess)
            {
                fileUpload();
                ConcreteRollBack();
            }
            else
            {
                Response.Write("<script>alert('您不具有当前访问权限！')</script>");
            }
        }
        private void ConcreteRollBack()
        {
            var db = new QuaManSysEntities();
            var query = (from p in db.InnerQualityInfo
                         where p.qualityInfoId == lblInfoNo.Text
                         select p).SingleOrDefault();
            switch (query.processingStatus)
            {
                case "分发":
                    query.processingStatus = "登记";
                    break;
                case "处理":
                    query.processingStatus = "分发";
                    break;
                default:
                    break;
            }

            //query.processingStatus = "分发";

            db.SaveChanges();

            Response.Redirect("SubmitSuccess.aspx");

        }
        #endregion

        #region 归档事件处理

        /// <summary>
        /// 内部质量信息归档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInfoSub_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "1B", "D1");
            if (roleAccess)
            {
                fileUpload();
                ConcreteInfoSub();
            }
            else
            {
                Response.Write("<script>alert('您不具有当前访问权限！')</script>");
            }
        }

        private void ConcreteInfoSub()
        {
            var db = new QuaManSysEntities();
            var query = (from p in db.InnerQualityInfo
                         where p.qualityInfoId == lblInfoNo.Text
                         select p).SingleOrDefault();
            query.processingStatus = "归档";
            query.processingResults = txtReqRsl.Text;
            query.processingAssess = txtProCmm.Text;
            db.SaveChanges();
            Response.Redirect("SubmitSuccess.aspx");

        }
        #endregion

        #region 登记事件处理

        /// <summary>
        /// 内部质量信息登记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRegist_Click(object sender, EventArgs e)
        {
            CurUser user = (CurUser)Session["curUser"];
            if (Permission.JudgePermission(user, "1A", "A"))
            {
                using (QuaManSysEntities context = new QuaManSysEntities())
                {
                    var db = from c in context.InnerQualityInfo
                             where c.qualityInfoId.Equals(lblInfoNo.Text)
                             select c;
                    if (db != null)
                    {
                        context.InnerQualityInfo.Remove(db.Single());
                        context.SaveChanges();
                    }
                }

                #region 内部质量信息登记

                try
                {
                    string infoCat = "";
                    if (CheckBox1.Checked) { infoCat = "已处理（需后继关注）"; CheckBox2.Enabled = false; }
                    if (CheckBox2.Checked) { infoCat = "未处理（需跟踪处理）"; CheckBox1.Enabled = false; }
                    fileUpload();
                    using (var db = new QuaManSysEntities())
                    {

                        InnerQualityInfo insertInner = new InnerQualityInfo
                        {
                            qualityInfoId = lblInfoNo.Text,
                            projectNo = ddlProNo.Text,
                            components = txtComponent.Text,
                            producer = txtManufac.Text,
                            faultType = txtFaiTyp.Text,
                            projectCategory = infoCat,
                            name = txtPjNam.Text,
                            deadline = Convert.ToDateTime(txtProDL.Text),
                            customerLinker = txtCustomer.Text,
                            telephone = txtCusTel.Text,
                            specialDemands = txtSpeReq.Text,
                            informationSource = DDLInfoCla.Text,
                            levelOfImportance = DDLImpLev.Text,
                            description = txtInfoDsc.Text,
                            registrantName = user.employeeId, //存放employeeID而不是name
                            registrantDepart = txtInfoDep.Text,
                            //registDate = Convert.ToDateTime(txtWrtDat.Text),
                            registDate = DateTime.Now.Date,
                            recommendedTreatPlan = txtReqAdv.Text,
                            processingStatus = "分发",
                            processingResults = txtReqRsl.Text,
                            processingAssess = txtProCmm.Text,
                            informationCategory = txtPjCls.Text
                        };
                        db.InnerQualityInfo.Add(insertInner);
                        db.SaveChanges();

                        InnerResponsibleDepart resDept = new InnerResponsibleDepart
                        {
                            department = DDLDepRes.Text,
                            qualityInfoId = lblInfoNo.Text,
                            isResponDepart = 1
                        };
                        db.InnerResponsibleDepart.Add(resDept);
                        db.SaveChanges();

                        Common.InnerRelatedDeptOperation.AddInnerRelatedDept(lblInfoNo.Text, user.department);

                        string ss = txtDeptFoc.Text.ToString();
                        if (ss != "")
                        {
                            string[] ssd = ss.Split('|');

                            for (int i = 0; i < ssd.Length; i++)
                            {

                                InnerResponsibleDepart dept = new InnerResponsibleDepart
                                {
                                    department = ssd[i],
                                    qualityInfoId = lblInfoNo.Text,
                                    isResponDepart = 0
                                };
                                db.InnerResponsibleDepart.Add(dept);
                                db.SaveChanges();

                            }
                        }



                    }

                    Response.Redirect("SubmitSuccess.aspx");

                }

                catch (Exception ex)
                {
                    Response.Write("<Script>alert('提交失误');</Script>");
                    throw ex;
                }
                #endregion
            }
            else
            {
                Response.Write("<Script>alert('权限不足，无法操作！');</Script>");
            }
            
        }
        #endregion

        #region 分发事件处理

        /// <summary>
        /// 内部质量信息分发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDistribute_Click(object sender, EventArgs e)
        {
            CurUser user = (CurUser)Session["CurUser"];
            if (Permission.JudgePermission(user, "1B", "B0"))
            {
                fileUpload();
                UpdateInfo(lblInfoNo.Text);
                InsertInfo();
                Common.InnerRelatedDeptOperation.AddInnerRelatedDept(lblInfoNo.Text, user.department);
                Response.Redirect("SubmitSuccess.aspx");
            }
            else
            {
                Response.Write("<Script>alert('权限不足，无法操作！');</Script>");
            }
            
        }

        /// <summary>
        /// 删除已有的数据
        /// </summary>
        private void UpdateInfo(string qualityInfoId)
        {
            using (var db = new QuaManSysEntities())
            {

                var query = (from q in db.InnerQualityInfo
                             where q.qualityInfoId == qualityInfoId
                             select q).Single();


                var query2 = from p in db.InnerResponsibleDepart
                             where p.qualityInfoId == qualityInfoId
                             select p;
                //db.Entry(query).Collection(d => d.InnerResponsibleDepart).Load();

                foreach (var p in query2)
                {
                    db.InnerResponsibleDepart.Remove(p);

                }
                db.SaveChanges();

            }
        }

        /// <summary>
        /// 质保部门修改后插入数据
        /// </summary>
        private void InsertInfo()
        {

            string infoCat = "";
            if (CheckBox1.Checked) infoCat = "已处理（需后继关注）";
            if (CheckBox2.Checked) infoCat = "未处理（需跟踪处理）";

            using (var db = new QuaManSysEntities())
            {
                var query = (from p in db.InnerQualityInfo
                             where p.qualityInfoId == lblInfoNo.Text
                             select p).First();

                query.projectNo = ddlProNo.Text;
                query.components = txtComponent.Text;
                query.producer = txtManufac.Text;
                query.faultType = txtFaiTyp.Text;
                query.projectCategory = infoCat;
                query.name = txtPjNam.Text;
                query.deadline = Convert.ToDateTime(txtProDL.Text);
                query.customerLinker = txtCustomer.Text;
                query.telephone = txtCusTel.Text;
                query.specialDemands = txtSpeReq.Text;
                query.informationSource = DDLInfoCla.Text;
                query.levelOfImportance = DDLImpLev.Text;
                query.description = txtInfoDsc.Text;
                //query.registrantName = txtInfoWrt.Text;
                //query.registrantDepart = txtInfoDep.Text;
                //registDate = Convert.ToDateTime(txtWrtDat.Text),
                query.registDate = DateTime.Now.Date;
                query.recommendedTreatPlan = txtReqAdv.Text;
                query.processingStatus = "处理";
                query.processingResults = txtReqRsl.Text;
                query.processingAssess = txtProCmm.Text;
                query.informationCategory = txtPjCls.Text;
                db.SaveChanges();

                InnerResponsibleDepart resDept = new InnerResponsibleDepart
                {
                    department = DDLDepRes.Text,
                    qualityInfoId = lblInfoNo.Text,
                    isResponDepart = 1
                };
                db.InnerResponsibleDepart.Add(resDept);
                db.SaveChanges();


                string ss = txtDeptFoc.Text.ToString();
                if (ss != "")
                {
                    string[] ssd = ss.Split('|');

                    for (int i = 0; i < ssd.Length; i++)
                    {

                        InnerResponsibleDepart dept = new InnerResponsibleDepart
                        {
                            department = ssd[i],
                            qualityInfoId = lblInfoNo.Text,
                            isResponDepart = 0
                        };
                        db.InnerResponsibleDepart.Add(dept);
                        db.SaveChanges();
                    }
                }
            }
        }
        #endregion

        #region 上传附件事件处理

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAttachment_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 下载附件事件处理

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnADownload_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 机型机号随工程编号改变自动改变，重新加载机型机号

        /// <summary>
        /// 自动显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
            
        }
        #endregion

        #region 重新加载责任部门和关注部门

        /// <summary>
        /// 重新加载checkbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ResponDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            initRelatedDept();
        }
        #endregion

        #region 登记人和归档人员处理结果评价

        protected void btnEvaluate_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            
            //判断当前用户是否具有评价权限
            bool roleAccessA = Permission.JudgePermission(user, "1A", "A");
            bool roleAccessB = Permission.JudgePermission(user, "1A", "D1");
            if (roleAccessA || roleAccessB)
            {
                fileUpload();
                ConcreteEvaluate();
            }
            else
            {
                ConcreteEvaluate(user);
            }
        }

        private void ConcreteEvaluate(CurUser user)
        {
            using (var db = new QuaManSysEntities())
            {
                var query = (from p in db.InnerQualityInfo
                             where p.qualityInfoId == lblInfoNo.Text
                             select p).SingleOrDefault();
                if (query.registrantName == user.employeeId)
                {
                    query.processingResults = txtReqRsl.Text;
                    query.processingAssess = txtProCmm.Text;
                    db.SaveChanges();
                    Response.Redirect("SubmitSuccess.aspx");
                }
                else
                {
                    Response.Write("<script>alert('您不具有当前访问权限！')</script>");
                }
            }
        }

        private void ConcreteEvaluate()
        {
            using (var db = new QuaManSysEntities())
            {
                var query = (from p in db.InnerQualityInfo
                             where p.qualityInfoId == lblInfoNo.Text
                             select p).SingleOrDefault();

                query.processingResults = txtReqRsl.Text;
                query.processingAssess = txtProCmm.Text;
                db.SaveChanges();
                Response.Redirect("SubmitSuccess.aspx");
            }
        }

        #endregion

        #region 提交数据库归档（已删除）

        /// <summary>
        /// 提交数据库归档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //   protected void btnInfoSub_Click(object sender, EventArgs e)
        //   {  
        //    string infoCat = "";
        //    if (CheckBox1.Checked) infoCat = "已处理（需后继关注）";
        //    if (CheckBox2.Checked) infoCat = "未处理（需跟踪处理）";

        //    using (var db = new QuaManSysEntities())
        //    { 

        //    InnerQualityInfo insertInner = new InnerQualityInfo
        //    {
        //        //qualityInfoId = lblNo.Text,
        //        projectNo = ddlProNo.Text,
        //        components = txtComponent.Text,
        //        producer = txtManufac.Text,
        //        faultType = txtFaiTyp.Text,
        //        projectCategory = infoCat,
        //        name = txtPjNam.Text,
        //        deadline = Convert.ToDateTime(txtProDL.Text),
        //        customerLinker = txtCustomer.Text,
        //        telephone = txtCusTel.Text,
        //        specialDemands = txtSpeReq.Text,
        //        informationSource = DDLInfoCla.Text,
        //        levelOfImportance = DDLImpLev.Text,
        //        description = txtInfoDsc.Text,
        //        registrantName = txtInfoWrt.Text,
        //        registrantDepart = txtInfoDep.Text,
        //        //registDate = Convert.ToDateTime(txtWrtDat.Text),
        //        registDate = DateTime.Now.Date,
        //        recommendedTreatPlan = txtReqAdv.Text,
        //        processingStatus = "分发",
        //        processingResults = txtReqRsl.Text,
        //        processingAssess = txtProCmm.Text,
        //        informationCategory = txtPjCls.Text
        //    };
        //    db.InnerQualityInfo.Add(insertInner);
        //    db.SaveChanges();

        //    InnerResponsibleDepart resDept = new InnerResponsibleDepart
        //    {
        //        department = DDLDepRes.Text,
        //        //qualityInfoId = lblNo.Text,
        //        isResponDepart = 1
        //    };
        //    db.InnerResponsibleDepart.Add(resDept);
        //    db.SaveChanges();


        //    string ss = DDLDepFoc.Text.ToString();
        //    string[] ssd = ss.Split('|');

        //    for( int i=0;i<ssd.Length;i++){

        //      InnerResponsibleDepart dept = new InnerResponsibleDepart
        //    {
        //        department = ssd[i],
        //        //qualityInfoId = lblNo.Text,
        //        isResponDepart = 0
        //    };
        //      db.InnerResponsibleDepart.Add(dept);
        //      db.SaveChanges();

        //    }


        //    }
        //}

        #endregion

        #region 文件上传
        protected void fileUpload()
        {
            #region
            int cnt = Convert.ToInt16(hidden.Value.ToString());
            HtmlInputFile f = this.FileUploadD1;
            UpLoadFile(f.PostedFile);

            for (int i = 2; i <= cnt; i++)
            {
                HttpPostedFile f1 = Request.Files["FileUploadD" + i];
                UpLoadFile(f1);
            }
            #endregion
        }

        /// <summary>
        /// 文件上传。
        /// </summary>
        /// <param name="InputFile"></param>
        /// <param name="Path"></param>
        public string UpLoadFile(HttpPostedFile InputFile)
        {

            //判断有控件内容进入
            string b = "";
            string xdd = "";
            try
            {
                xdd = InputFile.FileName.ToString();//获取上传文件的名字
            }
            catch (Exception e)
            {
                return xdd;
            }
            if (xdd != "")
            {
                string path = "~/FileUploadCS/" + lblInfoNo.Text + "/";

                string PRICE_FJ_FJMC = "";
                string PRICE_FJ_FJHZ = "";
                string PRICE_FJ_PATH_SC = "";
                string PRICE_FJ_PATH_XZ = "";

                PRICE_FJ_PATH_XZ = path;
                //上传全路径包括文件名G:\\新建文件夹 (4)\\新建 文本文档.txt
                PRICE_FJ_PATH_SC = InputFile.FileName;
                //文件名包括后缀 新建 文本文档.txt"
                PRICE_FJ_FJMC = PRICE_FJ_PATH_SC.Substring(PRICE_FJ_PATH_SC.LastIndexOf("\\") + 1);
                ////
                //建立上传对象
                //
                HttpPostedFile postedFile = InputFile;
                //文件名包括后缀 新建 文本文档.txt"
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //文件后缀
                PRICE_FJ_FJHZ = System.IO.Path.GetExtension(fileName);


                string phyPath = HttpContext.Current.Request.MapPath(PRICE_FJ_PATH_XZ);//获取文件所在根目录
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                //
                //保存文件
                //
                try
                {
                    postedFile.SaveAs(phyPath + PRICE_FJ_FJMC);//文件保存
                    return b = phyPath;

                }
                catch
                {
                    throw new ApplicationException("上传失败!");
                }
                //返回上传文件的信息
            }

            return b;
        }
        #endregion
        #region
        protected void btn_xz_Click(object sender, EventArgs e)
        {


            string path = "~/FileUploadCS/" + lblInfoNo.Text + "/";
            string phyPath = HttpContext.Current.Request.MapPath(path);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if (!upDir.Exists)
            {
                Response.Write("<script>alert('附件不存在')</script>");
                return;
            }
            string wjm = Server.UrlEncode(phyPath);//要进行编码的转换
            //Page.RegisterStartupScript("", " <script   language=javascript> window.open   ( '附件下载.aspx?wjm=" + wjm + " ','下载界面',   'height=300,   width=400,    toolbar=no,   menubar=no,   scrollbars=no,   resizable=no,  location=no,   status=no ') </script> ");
            Page.ClientScript.RegisterStartupScript(GetType(), "", " <script   language=javascript> window.open   ( 'attatchDownload.aspx?wjm=" + wjm + " ','下载界面',   'height=300,   width=400,    toolbar=no,   menubar=no,   scrollbars=no,   resizable=no,  location=no,   status=no ') </script> ");

        }
        #endregion

        protected void initAttatchment()
        {
            string path = "~/FileUploadCS/" + lblInfoNo.Text + "/";
            string phyPath = HttpContext.Current.Request.MapPath(path);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if (!upDir.Exists)
            {
                return;
            }
            FileInfo[] fileInfo = upDir.GetFiles();
            attatch.DataSource = fileInfo;
            attatch.DataBind();

        }

        protected void OnItemCommand(object sender, RepeaterCommandEventArgs e)
        {

            string path = "~/FileUploadCS/" + lblInfoNo.Text + "/" + e.CommandArgument;
            string phyPath = HttpContext.Current.Request.MapPath(path);
            if (e.CommandName == "delete")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                if (file.Exists)
                {
                    file.Delete();
                    foreach (RepeaterItem item in attatch.Items)
                    {
                        TextBox tb = (TextBox)item.FindControl("attatchName");
                        if (tb.Text == e.CommandArgument.ToString())
                        {
                            tb.Visible = false;
                            Button btn1 = (Button)item.FindControl("d1");
                            Button btn2 = (Button)item.FindControl("d2");
                            btn1.Visible = false;
                            btn2.Visible = false;
                        }
                    }
                }

            }
            else if (e.CommandName == "download")
            {
                FileInfo file = new System.IO.FileInfo(phyPath);
                Page.Response.Buffer = false;
                Page.Response.Charset = "UTF-8";
                Page.Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode((file.Name)));
                Page.Response.HeaderEncoding = System.Text.Encoding.UTF8;
                Page.Response.ContentEncoding = System.Text.Encoding.UTF8;//GetEncoding("UTF-8");
                Page.Response.ContentType = "application/ms-excel";
                Page.Response.WriteFile(file.FullName);
                //System.IO.File.Delete(file.FullName);
                Page.Response.End();
            }

        }
    }
}